package cn.edu.ctbu.lab.service.impl;

import cn.edu.ctbu.lab.dao.TeacherRepository;
import cn.edu.ctbu.lab.dao.TeacherRepository;
import cn.edu.ctbu.lab.domain.Teacher;
import cn.edu.ctbu.lab.exception.REnum;
import cn.edu.ctbu.lab.exception.RException;
import cn.edu.ctbu.lab.service.TeacherService;
import cn.edu.ctbu.lab.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherRepository teacherRepository;


    public Optional<Teacher> findById(Integer id){

        Optional<Teacher> teacher=teacherRepository.findById(id);
        return teacher;
    }


    public List<Teacher> findAll(){

        List<Teacher> myList=teacherRepository.findAll();
        return myList;
    }


    public  List<Teacher> findByNameAndPage(String name){
        List<Teacher> myList = teacherRepository.findByNameAndPage(name);
        return myList;
    }
    public Page<Teacher> findByPage(int pageIndex, int pageSize){

        Sort sort =  Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        Page<Teacher> myList=teacherRepository.findAll(pageable);

        return myList;

    }




    public Teacher add(Teacher teacher){
        teacherRepository.save(teacher);
        return teacher;
    }

    public Teacher update(Teacher Teacher){
        Teacher TeacherOld=teacherRepository.getOne(Teacher.getId());
        //todo sth....
        teacherRepository.save(Teacher);
        return Teacher;
    }


    public int delete(Teacher teacher){

        try{

            teacherRepository.delete(teacher);
        }catch (Exception e){

            //throw  e;
            return -1;
        }
        return 1;
    }

    public  int delete(Integer id){
        Teacher teacher=teacherRepository.getOne(id);

        return delete(teacher);

    }


    /**
     * 按学生的登录名和密码取学生，如果取到，那么返回此学生;如果取不到，扔出异常
     * @param name
     * @param password
     * @return
     */
    public Teacher validUserNoAndPassword(String name,String password) throws  Exception{

        List<Teacher> teachers=teacherRepository.findByNoAndPassword(name,password);
        if(teachers.size()==0){
            throw new RException(REnum.LOGIN_ERR);

        }

        return teachers.get(0);
    }
}